﻿using System;
using System.Data.Objects;
using System.Windows.Forms;

namespace CourseManager
{
	public partial class CourseViewer : Form
	{
		// Create an ObjectContext instance based on SchoolEntity.
		private SchoolEntities schoolContext;

		public CourseViewer()
		{
			InitializeComponent();
		}

		private void closeForm_Click(object sender, EventArgs e)
		{
			// Close the form.
			this.Close();

			// Dispose the object context.
			schoolContext.Dispose();
		}

		private void CourseViewer_Load(object sender, EventArgs e)
		{
			// Initialize the ObjectContext.
			schoolContext = new SchoolEntities();

			// Define a query that returns all Department objects and related
			// Course objects, ordered by name.
			ObjectQuery<Department> departmentQuery =
				schoolContext.Department.Include("Course").OrderBy("it.Name");

			try
			{
				// Bind the ComboBox control to the query, which is
				// executed during data binding.
				this.departmentList.DataSource = departmentQuery;
				this.departmentList.DisplayMember = "Name";
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void departmentList_SelectedIndexChanged(object sender, EventArgs e)
		{
			try
			{
				// Get the object for the selected department.
				Department department = (Department)this.departmentList.SelectedItem;
				
				// Bind the grid view to the collection of Course objects 
				// that are related to the selected Department object.
				courseGridView.DataSource = department.Course;

				courseGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void saveChanges_Click(object sender, EventArgs e)
		{
			try
			{
				int numChanges;
				// Save object changes to the database, display a message,
				// and refresh the form.
				numChanges = schoolContext.SaveChanges();
				MessageBox.Show(numChanges.ToString() +" change(s) saved to the database.");
				this.Refresh();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
	}
}
